<template>
    <div class="list-buttons">
        <div class="btns-box" :class="[{ compact: compact }]">
            <el-button
                v-if="buttons.indexOf('create') !== -1"
                type="primary"
                class="el-icon-plus"
                size="small"
                @click="handleCreate"
            >
                {{ compact ? '' : $t('lang.add') }}
            </el-button>
            <el-button
                v-if="buttons.indexOf('edit') !== -1"
                type="primary"
                class="el-icon-edit"
                size="small"
                @click="handleEdit"
            >
                {{ compact ? '' : $t('lang.edit') }}
            </el-button>
            <el-button
                v-if="buttons.indexOf('rebuild') !== -1"
                type="primary"
                class="icon icon-rotateClockwise"
                size="small"
                @click="handleRebuild"
            >
                {{ compact ? '' : $t('lang.repaint') }}
            </el-button>
            <el-button
                v-if="buttons.indexOf('clonePaths') !== -1"
                type="primary"
                class="icon icon-clone"
                size="small"
                @click="handleClonePath"
            >
                {{ compact ? '' : $t('lang.clone') }}
            </el-button>
            <el-button
                v-if="buttons.indexOf('cloneContour') !== -1"
                type="primary"
                class="icon icon-clone"
                size="small"
                @click="handleCloneContour"
            >
                {{ compact ? '' : $t('lang.clone') }}
            </el-button>
            <el-button
                v-if="buttons.indexOf('reset') !== -1"
                type="primary"
                class="icon icon-t-reset"
                size="small"
                @click="handleReset"
            >
                {{ compact ? '' : $t('lang.reset') }}
            </el-button>
            <el-button
                v-if="buttons.indexOf('startup') !== -1"
                type="warning"
                class="icon icon-startup"
                size="small"
                ref="editBtn"
                @click="handleStartup"
            >
                {{ compact ? '' : $t('lang.startup') }}
            </el-button>
            <el-button
                v-if="buttons.indexOf('active') !== -1"
                type="warning"
                class="icon icon-active"
                size="small"
                @click="handleActive"
            >
                {{ compact ? '' : $t('lang.active') }}
            </el-button>
            <el-button
                v-if="buttons.indexOf('lock') !== -1"
                type="warning"
                class="icon icon-t-lock"
                size="small"
                @click="handleLock"
            >
                {{ compact ? '' : $t('lang.lock') }}
            </el-button>
        </div>

        <div class="btns-box" :class="[{ compact: compact }]">
            <el-button
                v-if="buttons.indexOf('merge') !== -1"
                type="primary"
                class="icon icon-fullscreen-restore"
                size="small"
                @click="handleMerge"
            >
                {{ compact ? '' : $t('lang.merge') }}
            </el-button>
            <el-button
                v-if="buttons.indexOf('split') !== -1"
                type="primary"
                class="icon icon-fullscreen"
                size="small"
                @click="handleSplit"
            >
                {{ compact ? '' : $t('lang.split') }}
            </el-button>
        </div>
        <div class="btns-box" :class="[{ compact: compact }]">
            <el-button
                v-if="buttons.indexOf('upload') !== -1"
                type="info"
                class="icon icon-t-upload"
                size="small"
                @click="handleUpload"
            >
                {{ compact ? '' : $t('lang.upload') }}
            </el-button>
            <el-button
                v-if="buttons.indexOf('download') !== -1"
                type="info"
                class="icon icon-t-download"
                size="small"
                @click="handleDownload"
            >
                {{ compact ? '' : $t('lang.download') }}
            </el-button>
        </div>
        <!-- <el-dropdown trigger="click" @command="handleDownload">
            <el-button v-if="buttons.indexOf('download') !== -1" type="info" class="el-icon-download" size="small">
                {{ compact ? '' : $t('lang.download') }}
            </el-button>
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="JSON">JSON</el-dropdown-item>
                <el-dropdown-item command="Excel">Excel</el-dropdown-item>
            </el-dropdown-menu>
        </el-dropdown>-->

        <div class="btns-box" :class="[{ compact: compact }]">
            <el-button
                v-if="buttons.indexOf('delete') !== -1"
                type="danger"
                class="icon icon-t-del"
                size="small"
                @click="handleDelete"
            >
                {{ compact ? '' : $t('lang.delete') }}
            </el-button>
        </div>
        <slot></slot>
    </div>
</template>

<script type="text/ecmascript-6">
import * as utils from '../../utils/utils.js';
import * as Timer from '../../utils/Timer.js';
import * as API from '../../core/api.js';
import * as Chef from '../../core/Chef.js';
import bus from '../../utils/Eventbus.js';
import _ from 'lodash';
import i18n from '../../lang/index.js';
const $t = i18n.global.t;
export default {
    name: 'p-list-buttons',
    components: {},
    props: {
        compact: Boolean,
        readonly: Boolean,
        module: String,
        buttons: Array,
        ids: Array,
        list: Array,
        idsClearFunc: Function,
        beforeDeleteFunc: Function,
        multiSelect: Boolean
    },
    data () {
        return {
            detailName: ''
        };
    },
    computed: {
    },
    watch: {},
    mounted() {
        this.init();
    },
    methods: {
        init() {
            if (this.module === 'paths') {
              this.detailName =  'path';
            } else {
              this.detailName = this.module && this.module.replace(/[s]$/, '') || '';
            }
        },
        handleCreate() {
            // if (typeof this.idsClearFunc === 'function') this.idsClearFunc();
            this.$emit('clearIds', [-1]);
            if (!this.compact) this.$router.push({ name: `${this.detailName}-detail`, params: { type: 'add', ids: [-1] } });
            else this.$emit('editEnableChange', true);
        },
        handleEdit() {
            if (!this.ids || !this.ids.length)
                return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.detailName}`)));
            if (this.ids.length > 1 && !this.multiSelect)
                return this.$message.error($t('lang.maxSelection').format(1, $t(`lang.${this.detailName}`)));
            if (!this.compact) this.$router.push({ name: `${this.detailName}-detail`, params: { type: 'edit', ids: this.ids } });
            else this.$emit('editEnableChange', true);
        },
        handleRebuild() {
            API.loadScene();
        },
        async handleMerge(e, ids) {
            let cids = ids || this.ids;
            if (!cids || !cids.length)
                return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.detailName}`)));

            let res = await API.mergePaths(cids);
            console.warn('p-list-buttons.handleMerge...', cids, res);
            let type = 'info';
            if (!res || !res.successCount) type = 'error';
            else if (res && res.successCount === cids.length) type = 'success';
            if (res && res.successCount === 0) this.$message({ message: $t('lang.pathsMergedError'), type});
            else this.$message({ message: $t('lang.pathsMerged').format(res.successCount), type});
        },
        async handleSplit(e, ids) {
            console.warn('p-list-buttons.handleSplit...');
            let cids = ids || this.ids;
            if (!cids || !cids.length)
                return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.detailName}`)));

            let res = await API.splitPaths(cids);
            console.warn('p-list-buttons.handleSplit...', cids, res);
            let type = 'info';
            if (!res || !res.successCount) type = 'error';
            else if (res && res.successCount === cids.length) type = 'success';
            if (res && res.successCount === 0) this.$message({ message: $t('lang.pathsSplitError'), type});
            else this.$message({ message: $t('lang.pathsSplit').format(res.successCount), type});
        },
        async handleClonePath(e, ids) {
            console.warn('p-list-buttons.handleClonePath...');
            let cids = ids || this.ids;
            // 删除dis -1
            let newIds = _.cloneDeep(cids);
            if (newIds.includes('-1')) {
                let idx = newIds.indexOf('-1');
                newIds.splice(idx, 1);
            }
            cids = newIds;
            if (!cids || !cids.length)
                return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.module}`)));

            let res = await API.filterLocalResources('paths', cids);
            console.warn('p-list-buttons.handleClonePath...', res.list);
            if (!res || !res.list || !res.list.length) return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.detailName}`)));
            let os = res.list;
            os.forEach(v => v.id = -1);

            this.$emit('clearIds', [-1]);
            if (!this.compact) this.$router.push({ name: `${this.detailName}-detail`, params: { type: 'add', ids: [-1], locals: os } });
            else {
                this.$emit('editEnableChange', true);
                bus.emit('p-path-detail-form.init', os);
            }
        },
        async handleCloneContour(e, ids) {
            let cids = ids || this.ids;
            // 删除dis -1
            let newIds = _.cloneDeep(cids);
            if (newIds.includes('-1')) {
                let idx = newIds.indexOf('-1');
                newIds.splice(idx, 1);
            }
            cids = newIds;
            if (!cids || !cids.length)
                return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.module}`)));

            let res = await API.filterLocalResources('contours', cids);
            console.warn('p-list-buttons.handleCloneContour...', res.list);
            if (!res || !res.list || !res.list.length) return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.detailName}`)));
            let os = res.list;
            os.forEach(v => v.id = -1);

            this.$emit('clearIds', [-1]);
            if (!this.compact) this.$router.push({ name: `${this.detailName}-detail`, params: { type: 'add', ids: [-1], locals: os } });
            else {
                this.$emit('editEnableChange', true);
                bus.emit('contoursEditor.init', os);
            }
        },
        handleReset(e, ids) {
            let cids = ids || this.ids;
            console.warn('handle job reset...', cids);
            if (!cids || !cids.length) return;
            API.updateJobsReset(cids);
        },
        handleStartup(e, ids) {
            let cids = ids || this.ids;
            if (!cids || !cids.length)
                return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.detailName}`)));

            let num = 0;
            cids.forEach(id => num += this.list.find(v => v.id === id).properties.startup === 'true');
            let val = String(num !== cids.length);
            API.toggleUpdates(this.module, cids, 'startup', val, e.target || e.srcElement);
        },
        handleActive(e, ids) {
            let cids = ids || this.ids;
            if (!cids || !cids.length)
                return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.detailName}`)));
            let num = 0;
            cids.forEach(id => num += this.list.find(v => v.id === id).properties.activation === 'true');
            let val = String(num !== cids.length);
            API.toggleUpdates(this.module, cids, 'activation', val, e.target || e.srcElement);
        },
        async handleDelete(e, ids) {
            let cids = ids || this.ids;
            // 删除dis -1
            let newIds = _.cloneDeep(cids);
            if (newIds.includes('-1')) {
                let idx = newIds.indexOf('-1');
                newIds.splice(idx, 1);
            }
            cids = newIds;
            if (!cids || !cids.length)
                return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.detailName}`)));
            let len = cids.length,
                module = len > 1 ? $t(`lang.${this.module}`) : $t(`lang.${this.detailName}`),
                con = $t('lang.deletionWarning').format(len, module),
                success = $t('lang.resource') + ' ' + $t('lang.deleted');
            // if (typeof this.beforeDeleteFunc === 'function') await this.beforeDeleteFunc(cids);
            this.$confirm(con, $t('lang.warning'), {
                type: 'warning',
                confirmButtonText: $t('lang.ok'),
                cancelButtonText: $t('lang.cancel')
            }).then(() => {
                if (typeof this.beforeDeleteFunc === 'function') this.beforeDeleteFunc(cids);
                API.batchDelete(this.module, cids).then(() => {
                    this.$message({ type: 'success', message: success });
                    bus.emit('p-table.init');
                    bus.emit('p-painter.clearLocals');
                    if (this.compact) {
                        bus.emit('p-panel.editEnableChange', false);
                        bus.emit(this.module + '.toggleRowSelection', []);
                    }
                }).catch(() => {
                });
            }).catch(() => {
            });
        },
        handleLock(e, ids) {
            let cids = ids || this.ids;
            if (!cids || !cids.length)
                return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.detailName}`)));

            let num = 0;
            cids.forEach(id => num += this.list.find(v => v.id === id).properties.lock === 'true');
            let val = String(num !== cids.length);
            API.toggleUpdates(this.module, cids, 'lock', val, e.target || e.srcElement).then(() => {
                if (val === 'true') this.$message({ type: 'success', message: $t('lang.lockSuccess') });
                else this.$message({ type: 'success', message: $t('lang.unlockSuccess') });
            });
        },
        handleUpload() {
            console.log('models.handleUpload: ', ...arguments);
            this.$router.push({ name: 'upload-detail', params: { modules: this.module } });
        },
        handleDownload(command) {
            console.log('models.handleDownload: ', ...arguments);
            if (command === 'Excel') {
                console.log('走接口生成EXCEL');
                return;
            }
            let fileContent = this.$root.resources[this.module],
                shakefileContent = [],
                fileName = this.module;
            if (this.ids.length > 0) {
                fileContent = [];
                this.ids.forEach(id => {
                    fileContent.push(this.$root.resources[this.module].find(v => v.id === id));
                });
            }
            // let cids = this.ids;
            // if (!this.multiSelect && (!cids || !cids.length))
            //     return this.$message.error($t('lang.minSelection').format(1, $t(`lang.${this.detailName}`)));
            // if (!this.multiSelect && (cids && cids.length > 1))
            //     return this.$message.error($t('lang.maxSelection').format(1, $t(`lang.${this.detailName}`)));
            // if (!this.multiSelect) {
            //     fileContent = this.$root.resources[this.module].find(v => v.id === cids[0]);
            //     // fileContent = this.list.find(v => v.id === cids[0]);
            //     if (fileContent && fileContent.id) fileName = fileContent.id;
            // }
            /**
             * this.module首字母大写，module.slice(0, -1)删除最后一个字符
             * @type {string}
             */
            let module = this.module.replace(/\b(\w)|\s(\w)/g,function(m){
                return m.toUpperCase();
            });
            if (fileContent) {
                if (Array.isArray(fileContent) && fileContent.length > 0) {
                    fileContent.map(item => {
                        shakefileContent.push(Chef['shake' + module.slice(0, -1)](item));
                    });
                } else {
                    fileContent = Chef['shake' + module.slice(0, -1)](fileContent);
                }
            }
            // console.error(fileName, 'shake' + module.slice(0, -1), newfileContent);
            if (shakefileContent.length > 0) fileContent = shakefileContent;
            let text = JSON.stringify(fileContent, null, 2),
                blob = new Blob([text], { type: 'text/plain' });
            utils.download(`${process.env.VUE_APP_PROJECT_NAME}.${fileName}.${Timer.formatTime(Date.now(), 'yyyyMMdd')}.json`, URL.createObjectURL(blob));
        }
    }
};
</script>

<style lang="scss">
.list-buttons {
    display: inline-block;
    .el-dropdown {
        margin: 0 10px;
    }
    .btns-box {
        display: inline-block;
        margin-left: 5px;
    }
    .compact {
        background: #fff;
        border-radius: 3px;
        .el-button--primary,
        .el-button--warning,
        .el-button--danger,
        .el-button--info {
            background: transparent;
            color: #b6b9c0;
            border: none;
        }
    }
}
</style>
